<script setup lang="ts">
  import { ref, shallowRef, computed, watch, onMounted } from 'vue';
  import { Button } from '@arco-design/web-vue';
  import EmojiPicker from '/@/components/EmojiPicker.vue';
  import { Upload } from '/@/components/Upload';
  import type { FileItem } from '/@/components/Upload';
  import imgIcon from '/@/assets/pins/c_img.svg';
  import { OnClickOutside } from '@vueuse/components';
  import { isDef } from '/@/utils/is';
  import emojiIcon from '/@/assets/pins/c_emoji.svg';
  import { IconClose } from '@arco-design/web-vue/es/icon';
  import { SimpleEditor } from '/@/components/SimpleEditor';
  import type { ISimpleEditor } from '/@/components/SimpleEditor';

  interface CommentActionProps {
    defaultActionVisible?: boolean;
    actionVisible?: undefined | boolean;
    placeholder?: string;
    comment?: string;
    autoFocus?: boolean;
  }
  const props = withDefaults(defineProps<CommentActionProps>(), {
    defaultActionVisible: false,
    actionVisible: undefined,
    placeholder: '输入评论',
    autoFocus: true,
  });

  const emit = defineEmits<{
    (event: 'comment', content?: string, file?: string): void | Promise<void>;
    (event: 'update:action-visible', visible: boolean): void;
    (event: 'update:comment', content?: string): void;
    (event: 'change-action-visible', visible: boolean): void;
  }>();

  const commentRef = ref(props.comment);
  const fileListRef = ref<FileItem[]>([]);
  const getFile = computed(() => {
    return fileListRef.value?.[0];
  });
  const actionVisibleRef = ref(props.actionVisible ?? props.defaultActionVisible);
  const getActionVisible = computed(() => {
    const isFocus = isDef(props.actionVisible) ? props.actionVisible : actionVisibleRef.value;
    const hasFile = !!getFile.value;
    return isFocus || hasFile;
  });
  const editorRef = shallowRef<ISimpleEditor>();

  const onEmojiSelect = (i: string) => {
    editorRef.value?.insertHtml(i);
  };

  const onComment = async () => {
    await emit('comment', commentRef.value, getFile.value?.url);
    // changeActionVisible(false);
    editorRef.value?.clear();
  };

  const changeActionVisible = (visible: boolean) => {
    if (actionVisibleRef.value !== visible) {
      emit('change-action-visible', visible);
    }
    if (isDef(props.actionVisible)) {
      emit('update:action-visible', visible);
    } else {
      actionVisibleRef.value = visible;
    }
  };

  const onPictureClose = () => {
    fileListRef.value = [];
  };

  const onFileListChange = (fileList: FileItem[]) => {
    if (fileList.length > 0) {
      fileListRef.value = [fileList[fileList.length - 1]];
    } else {
      fileListRef.value = [];
    }
  };

  const onCreated = (editor: ISimpleEditor) => {
    editorRef.value = editor;
  };

  const changeComment = (val: string) => {
    if (isDef(props.comment)) {
      emit('update:comment', val);
    } else {
      commentRef.value = val;
    }
  };

  watch(
    () => props.comment,
    () => {
      commentRef.value = props.comment;
    },
  );

  onMounted(() => {
    if (props.autoFocus) {
      editorRef.value?.focus();
    }
  });
</script>

<template>
  <OnClickOutside
    :options="{ ignore: ['.arco-trigger-popup'] }"
    :capture="false"
    @trigger="changeActionVisible(false)"
  >
    <div @click="changeActionVisible(true)">
      <div
        class="transition-all border-[1px] border-gray-200 bg-gray-200 relative flex flex-col min-h-[38px] rounded-[4px]"
        :class="{ '!border-[#5f70ff] !bg-white': getActionVisible }"
      >
        <SimpleEditor :comment="commentRef" @change="changeComment" @on-created="onCreated" />
        <div
          class="absolute left-[12px] top-[8px] select-none pointer-events-none text-gray-500"
          v-if="!commentRef"
          >{{ props.placeholder }}</div
        >
        <div v-if="getFile" class="w-[64px] h-[64px] mx-[12px] mb-[12px] relative">
          <img class="w-full h-full object-cover" :src="getFile.url" />
          <div
            class="absolute right-0 top-0 bg-gray-400 w-[12px] h-[12px] text-[12px] flex text-white hover:bg-gray-300 cursor-pointer"
            @click="onPictureClose"
            ><IconClose
          /></div>
        </div>
      </div>
      <div class="mt-[8px] flex justify-between items-center" v-if="getActionVisible">
        <div class="flex items-center justify-center space-x-[24px]">
          <EmojiPicker @select="onEmojiSelect">
            <div class="flex items-center justify-center hover:text-[#5f70ff] cursor-default">
              <img :src="emojiIcon" class="w-[20px] h-[20px] mr-[8px]" />
              <div>表情</div>
            </div>
          </EmojiPicker>
          <Upload
            class="w-auto"
            :file-list="fileListRef"
            :list-type="'text'"
            :show-upload-list="false"
            :limit="2"
            @change="onFileListChange"
          >
            <div class="hover:text-[#5f70ff] flex items-center cursor-default">
              <img :src="imgIcon" class="w-[23px] h-[18px] mr-[8px]" />图片
            </div>
          </Upload>
        </div>
        <div>
          <Button type="primary" :disabled="!commentRef" @click.stop="onComment">发表评论</Button>
        </div>
      </div>
    </div>
  </OnClickOutside>
</template>
